package service

import (
	"accountInfoServer/model"
	"crypto/md5"
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"time"
)

// UserService 用户服务接口
type UserService interface {
	CheckLoginStatus(wpsSid string) (*model.LoginStatusResponse, error)
	GetUserInfo(wpsSid string, userID int) (*model.UserInfoResponse, error)
}

// userService 服务实现
type userService struct {
	client    *http.Client
	accessID  string
	secretKey string
}

// NewUserService 创建新的用户服务实例
func NewUserService(proxyAddr, accessID, secretKey string) (UserService, error) {
	client, err := createProxyClient(proxyAddr)
	if err != nil {
		return nil, err
	}

	return &userService{
		client:    client,
		accessID:  accessID,
		secretKey: secretKey,
	}, nil
}

// 创建带代理的HTTP客户端
func createProxyClient(proxyAddr string) (*http.Client, error) {
	proxyURL, err := url.Parse(proxyAddr)
	if err != nil {
		return nil, fmt.Errorf("代理地址解析失败: %v", err)
	}

	return &http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyURL(proxyURL),
		},
	}, nil
}

// 生成Content-Md5
func (s *userService) genContentMd5(uri string) string {
	sum := md5.Sum([]byte(uri))
	return hex.EncodeToString(sum[:])
}

// 生成Authorization签名头
func (s *userService) genAuthorization(uri, date string) string {
	contentMd5 := s.genContentMd5(uri)
	contentType := "application/json"
	signStr := s.secretKey + contentMd5 + contentType + date

	h := sha1.New()
	h.Write([]byte(signStr))
	signature := hex.EncodeToString(h.Sum(nil))

	return fmt.Sprintf("WPS-2:%s:%s", s.accessID, signature)
}

// 获取当前时间的RFC1123格式字符串
func (s *userService) getRFC1123Date() string {
	return time.Now().UTC().Format(time.RFC1123)
}

// 检查用户是否在线并获取用户ID
func (s *userService) CheckLoginStatus(wpsSid string) (*model.LoginStatusResponse, error) {
	uri := "/api/v3/islogin"
	date := s.getRFC1123Date()
	authorization := s.genAuthorization(uri, date)
	contentMd5 := s.genContentMd5(uri)

	req, err := http.NewRequest("GET", "https://account.wps.cn/api/v3/islogin", nil)
	if err != nil {
		return nil, fmt.Errorf("创建请求失败: %v", err)
	}

	req.Header.Set("Authorization", authorization)
	req.Header.Set("Content-Md5", contentMd5)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Date", date)
	req.Header.Set("Cookie", fmt.Sprintf("wps_sid=%s", wpsSid))

	resp, err := s.client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("发送请求失败: %v", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应失败: %v", err)
	}

	var loginStatus model.LoginStatusResponse
	if err := json.Unmarshal(body, &loginStatus); err != nil {
		return nil, fmt.Errorf("解析响应失败: %v, 响应内容: %s", err, string(body))
	}

	return &loginStatus, nil
}

// 根据用户ID获取用户信息
func (s *userService) GetUserInfo(wpsSid string, userID int) (*model.UserInfoResponse, error) {
	uri := fmt.Sprintf("/api/user/%d", userID)
	date := s.getRFC1123Date()
	authorization := s.genAuthorization(uri, date)
	contentMd5 := s.genContentMd5(uri)

	url := fmt.Sprintf("https://account.wps.cn/api/user/%d", userID)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, fmt.Errorf("创建请求失败: %v", err)
	}

	req.Header.Set("Authorization", authorization)
	req.Header.Set("Content-Md5", contentMd5)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Date", date)
	req.Header.Set("Cookie", fmt.Sprintf("wps_sid=%s", wpsSid))

	resp, err := s.client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("发送请求失败: %v", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应失败: %v", err)
	}

	var userInfo model.UserInfoResponse
	if err := json.Unmarshal(body, &userInfo); err != nil {
		return nil, fmt.Errorf("解析响应失败: %v, 响应内容: %s", err, string(body))
	}

	return &userInfo, nil
}
